package com.wgw.first.loginRegister;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wgw.first.R;
import com.wgw.first.app.MainActivity;
import com.wgw.first.cart.utils.CartStorage;
import com.wgw.first.home.bean.GoodssBean;
import com.wgw.first.utils.CacheUtils;
import com.wgw.first.utils.Constants;
import com.wgw.first.utils.StreamUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.wgw.first.cart.utils.CartStorage.JSON_CART;

/**
 * @author Admin
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class LoginActivity extends AppCompatActivity {

    private static final int GET_SERVER_RESOPENSE = 1;
    private static final int GET_ERROR = 2;
    private Button mNew_register;
    private Button mlogin;
    private EditText musername;
    private EditText mpassword;
    private String  username;
    private String  password;
    private GoodssBean goodssBean;

    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch(msg.what){
                //密码正确
                case GET_SERVER_RESOPENSE:
                    Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    System.out.println("qian");
                    //一开始登录先上传用户的购物车数据，添加那些还没同步的商品
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String json_cart = CacheUtils.getString(LoginActivity.this, JSON_CART)+"@"+Constants.ALEADYLOGIN;
                                System.out.println("上传购物车数据MainActivity:json_cart" + json_cart);
                                RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"),
                                        "jsoncart="+json_cart);
                                //                    RequestBody requestBody = new FormBody.Builder()
                                //                            .add("jsoncart",json_cart)
                                //                            .build();
                                OkHttpClient client = new OkHttpClient();
                                Request request = new Request.Builder()
                                        .url(Constants.BASE + Constants.UPCARTJSON)
                                        .post(requestBody)
                                        .build();
                                Response response = client.newCall(request).execute();
                                String responsedata = response.body().string();
                                System.out.println("responsedata" + responsedata);
                                getDataFromNet();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    //UpCartData.sendRequestWithOkHttp(LoginActivity.this);
                    System.out.println("hou");

                    //进行购物车数据的同步
                    //1，从服务器下载购物车数据





                    break;
                //密码错误
                case GET_ERROR:
                    Toast.makeText(LoginActivity.this,"登录失败，用户名或密码错误",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    public void getDataFromNet() {
        OkHttpUtils
                .get()
                .addParams("username",username)
                .url(Constants.BASE+Constants.DOWNSHOPPINGCART)
                //.url("http://192.168.191.1:8080/Product/HomeServlet")
                .id(100)
                .build()
                .execute(new MyStringCallback());
    }
    public class MyStringCallback extends StringCallback {

        @Override
        public void onError(Call call, Exception e, int id) {
            Log.e("TAG", "联网失败" + e.getMessage());
        }

        @Override
        public void onResponse(String response, int id) {

            switch (id) {
                case 100:
                    if (response != null) {
                        System.out.println("下载下来的购物车数据：" + response);
                        //2.删除之前本地的购物车数据
                        CartStorage cartStorage = CartStorage.getInstance(LoginActivity.this);
                        List<GoodssBean.Goods> datas = cartStorage.getDataFromLocal();
                        for (int i = 0; i < datas.size(); i++) {

                            cartStorage.deleteData(datas.get(i));

                        }
                        //如果response为空，就不解析了
                        //对response进行json解析
                        int a = response.indexOf("{");
                        int b = response.lastIndexOf("}");
                        System.out.println("a:"+a);
                        System.out.println("b:"+b);
                        System.out.println("111" + response.substring(a+1,b).trim());
                        Boolean boo = !response.substring(a+1,b).trim().equals("");
                        System.out.println(boo);
                        if(!response.substring(a+1,b).trim().equals("")){
                            processData(response);
                            //3，往本地购物车加入下载下来的数据

                            for (int i = 0; i < goodssBean.getGoods().size(); i++) {
                                goodssBean.getGoods().get(i).setUsername(Constants.ALEADYLOGIN);
                                CartStorage.getInstance(LoginActivity.this).addData(goodssBean.getGoods().get(i));
                            }

                        }
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();

                    }
                    break;
                case 101:
                    //                    Toast.makeText(mContext, "https", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private void processData(String json) {

        if (!TextUtils.isEmpty(json)) {
            JSONObject GoodssBean = JSON.parseObject(json, com.wgw.first.home.bean.GoodssBean.class);

            String goods = GoodssBean.getString("goods");

            goodssBean = new GoodssBean();

            List<GoodssBean.Goods> goodss = JSON.parseArray(goods, com.wgw.first.home.bean.GoodssBean.Goods.class);
            goodssBean.setGoods(goodss);
            for(int i = 0 ;i<goodss.size();i++){
                System.out.println("下载下来的数据");
                System.out.println(goodss.get(i).getISBN());
            }
            System.out.println(goodssBean.toString());
        }

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        mNew_register = (Button)findViewById(R.id.new_register);
        mlogin = (Button) findViewById(R.id.login);

        //文本框按钮
        musername = (EditText) findViewById(R.id.userName);
        mpassword = (EditText) findViewById(R.id.passWord);


    }

    /**
     * 登录，点击登录即跳转到软件主界面进行使用
     */
    public void click_login(View v) {


        //获取输入的用户名和密码
        username = musername.getText().toString().trim();
        password = mpassword.getText().toString().trim();
        System.out.println("点击登陆");
        //点击登录首先要进行用户密码验证，验证正确后才可以登录
        new Thread(){
            public void run(){
                System.out.println("进入run子线程");
                try {


                    //String path = "http://172.25.154.22:8080/Product/LoginServlet?username="+username+"&password="+ password;
                    String path = Constants.BASE + Constants.LOGIN+"?username="+username+"&password="+ password;
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    int code = conn.getResponseCode();
                    if(code == 200){
                        InputStream is = conn.getInputStream();
                        String  result = StreamUtils.readStream(is,2);
                        System.out.println(result);
                        if(result.contains("1")){
                            Message msg = Message.obtain();
                            msg.what = GET_SERVER_RESOPENSE;
                            msg.obj = result;
                            Constants.ALEADYLOGIN = username;
                            handler.sendMessage(msg);
                        }else{
                            Message msg = Message.obtain();
                            msg.what = GET_ERROR;
                            handler.sendMessage(msg);
                        }

                    }else{
                        Message msg = Message.obtain();
                        //msg.what =
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = GET_ERROR;
                    handler.sendMessage(msg);

                }
            }
        }.start();

    }

    /**
     *  注册,点击注册按钮即跳转到用户注册界面
     * @param v
     */

    public void new_register(View v){
        Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
        startActivity(intent);

    }
}
